var gulp = require("gulp");
const fs = require('fs');
const path = require('path');
const join = require('path').join;
const del = require('del');
const sourcemaps = require('gulp-sourcemaps');
const sass = require('gulp-sass');
const eslint = require('gulp-eslint');

var exec = require('child_process').exec;

const sourceDir = 'src';
var gulpConfig = {
    destDir: "./dist",
    otherSource: `${sourceDir}/**/*.!(scss|ts|tsx)`,
    styleSource: `${sourceDir}/**/*.scss`
}

const sourceMapOutDir = '.';
const sourceMapOptions = { includeContent: false, sourceRoot: '../src' };

const ts = require('gulp-typescript');
const tsProject = ts.createProject('tsconfig.json');

const styleLintOptions = {
    reporters: [{ formatter: 'string', console: true }],
    failAfterError: false
};

// 删除dist目录
function cleanDist() {
    return del(`${gulpConfig.destDir}/**`);
}

// 复制除源码外的其他文件到指定路径
function copyResources() {
    return gulp.src(gulpConfig.otherSource).pipe(gulp.dest(gulpConfig.destDir));
}

// 单独进行基本eslint
function lintScript() {
    return gulp.src(gulpConfig.scriptSource)
        .pipe(eslint())
        .pipe(eslint.format());
}




function compileStyle() {
    return gulp.src(gulpConfig.styleSource)
        .pipe(sourcemaps.init())
        .pipe(sass.sync().on('error', sass.logError))
        .pipe(sourcemaps.write(sourceMapOutDir, sourceMapOptions))
        .pipe(gulp.dest(gulpConfig.destDir));
}

// 编译ts文件 强制eslint 包含ts和d.ts的sourcemap
function compileScript() {
    return tsProject
        .src()
        .pipe(sourcemaps.init())
        .pipe(tsProject())
        .pipe(sourcemaps.write(sourceMapOutDir, sourceMapOptions))
        .pipe(gulp.dest(gulpConfig.destDir));
}


// ======== 任务列表 ========
// 清理dist目录
exports.cleanDist = cleanDist;


//编译scss
exports.compileStyle = compileStyle;

// 单独eslint
exports.lintScript = lintScript;

//编译ts
exports.compileScript = compileScript;

let compile = gulp.series(cleanDist, gulp.parallel(copyResources, compileStyle, compileScript));
// 默认任务是编译
exports.default = compile;


//src下一级文件夹生成export到根目录下的index.tsx 
function findSync(startPath) {
    let files = fs.readdirSync(startPath);
    result = [];
    files.forEach((val, index) => {
        let fPath = join(startPath, val);
        let stats = fs.statSync(fPath);
        if (stats.isDirectory()) {
            result.push(val);
        };
    });
    return result
}

gulp.task("createEntry", function () {
    let fileNames = findSync('./src')

    var arr = [];
    var notArr = ['util'];
    fileNames.forEach(item => {
        if (notArr.indexOf(item) == -1) {
            arr.push(`export * from \'./src\/${item}\'`)
        }
    })

    fs.writeFile('./index.tsx', arr.join('\r\n'), function (error) {
        if (error) {
            console.log('============写入失败============')
        } else {
            console.log('============写入成功=============')
        }
    });
});






